'use client'

import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useRouter } from 'next-nprogress-bar'
import Image from 'next/image'
import { CSSTransition } from 'react-transition-group'
import { Link } from '@/src/navigation'
import { usePathname } from 'next/navigation'
import { useBarFloat } from '../hooks/useBarFloat'
import Overlay from './overlay'
import Search from './search'
import BurgetMenu from './burger-menu'
import {
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
} from '@nextui-org/react'

import searchWhiteIcon from '@/public/search_white.png'
import searchBlackIcon from '@/public/search_black.png'
import phoneIcon from '@/public/phone.png'
import geoWhiteIcon from '@/public/geo_white.png'
import geoBlackIcon from '@/public/geo_black.png'
import cheveronBottomWhiteIcon from '@/public/cheveron_bottom_white.png'
import cheveronBottomBlackIcon from '@/public/cheveron_bottom_black.png'
import pointerGreenIcon from '@/public/pointer_green.png'
import pointerBlackIcon from '@/public/pointer_black.png'
import arrowRightGreenFill from '@/public/arrow_right_green_fill.png'

/* ------------------------------ NavItem START ----------------------------- */
interface NavItemProps {
  path: string
  isSelected: boolean
  children: React.ReactNode
  dropdownItems: {
    label: string
    path: string
  }[]
  isFloat: boolean
}

const NavItem: React.FC<NavItemProps> = (props) => {
  const { path, isSelected, children, dropdownItems, isFloat } = props
  const [isHover, setIsHover] = useState(false)
  const dropDownRef = useRef(null)

  return (
    <Link href={path} scroll>
      {/* 外层容器，用于 Hover 时改变颜色 */}
      <div
        className='group/item relative hover:bg-[#91B01C] hover:text-white cursor-pointer'
        onMouseEnter={() => setIsHover(true)}
        onMouseLeave={() => setIsHover(false)}
        onClick={() => setIsHover(false)}
      >
        {/* 内层容器，用于添加 Border Bottom */}
        <div
          className={`flex items-center mx-[1.0625rem] 2xl:mx-[1.625rem] py-[2.0625rem] 2xl:py-[3.0625rem] ${
            isSelected
              ? 'border-b-[3px] border-b-[#91B01C]'
              : 'border-b-[3px] border-b-transparent'
          }`}
        >
          {/* Label 文本 */}
          <div
            className={`text-[0.75rem] leading-[0.75rem] 2xl:text-[1.125rem] 2xl:leading-[1.125rem] ${
              isSelected ? 'text-[#91B01C] group-hover/item:text-white' : ''
            }`}
          >
            {children}
          </div>
          <div className='w-[0.25rem] 2xl:w-[0.375rem]'></div>
          {/* Cheveron Bottom 图标 START */}
          {dropdownItems.length > 0 && (
            <div className='relative mt-[0.1rem] 2xl:mt-[0.2rem] w-[0.4375rem] h-[0.25rem] 2xl:w-[0.625rem] 2xl:h-[0.375rem]'>
              {/* 常规状态 */}
              <div className='absolute top-0 left-0 w-[0.4375rem] h-[0.25rem] 2xl:w-[0.625rem] 2xl:h-[0.375rem]'>
                <Image
                  src={cheveronBottomWhiteIcon}
                  alt='cheveron icon'
                  fill
                  sizes='(max-width: 1024px) 0.4375rem, 0.625rem'
                />
              </div>
              {/* Header Hover 时 */}
              <div
                className={`${
                  isFloat ? 'block' : 'hidden'
                } absolute top-0 left-0 group-hover:block w-[0.4375rem] h-[0.25rem] 2xl:w-[0.625rem] 2xl:h-[0.375rem]`}
              >
                <Image
                  src={cheveronBottomBlackIcon}
                  alt='cheveron icon'
                  fill
                  sizes='(max-width: 1024px) 0.4375rem, 0.625rem'
                />
              </div>
              {/* NavItem Hover 时 */}
              <div className='absolute top-0 left-0 hidden group-hover/item:block w-[0.4375rem] h-[0.25rem] 2xl:w-[0.625rem] 2xl:h-[0.375rem]'>
                <Image
                  src={cheveronBottomWhiteIcon}
                  alt='cheveron icon'
                  fill
                  sizes='(max-width: 1024px) 0.4375rem, 0.625rem'
                />
              </div>
            </div>
          )}
          {/* Cheveron Bottom 图标 END */}
        </div>

        {/* Hover 时弹出的菜单 */}
        <CSSTransition
          nodeRef={dropDownRef}
          in={isHover}
          timeout={200}
          classNames='nav-item-dropdown'
          unmountOnExit
        >
          <div
            ref={dropDownRef}
            className='absolute bg-white rounded-[0.625rem] w-auto min-w-[9.8125rem]'
          >
            {dropdownItems.map((item) => {
              return (
                <Link href={`${path}${item.path}`} key={item.path}>
                  <div className='group/dropdown-item flex items-center px-[0.8125rem] py-[0.9375rem] 2xl:px-[1.25rem] 2xl:py-[1.375rem] w-auto'>
                    <div className='relative w-[1.0625rem] h-[0.8125rem] 2xl:w-[1.5625rem] 2xl:h-[1.1875rem] flex-shrink-0'>
                      <div className='group-hover/dropdown-item:hidden absolute top-0 left-0 w-[1.0625rem] h-[0.8125rem] 2xl:w-[1.5625rem] 2xl:h-[1.1875rem]'>
                        <Image
                          src={pointerBlackIcon}
                          alt='pointer icon'
                          fill
                          sizes='(max-width: 1024px) 1.0625rem, 1.5625rem'
                        />
                      </div>
                      <div className='hidden group-hover/dropdown-item:block absolute top-0 left-0 w-[1.0625rem] h-[0.8125rem] 2xl:w-[1.5625rem] 2xl:h-[1.1875rem]'>
                        <Image
                          src={pointerGreenIcon}
                          alt='pointer icon'
                          fill
                          sizes='(max-width: 1024px) 1.0625rem, 1.5625rem'
                        />
                      </div>
                    </div>
                    <div className='w-[0.4375rem] 2xl:w-[0.75rem]'></div>
                    <div className='text-[0.75rem] 2xl:text-[1.125rem] text-[#333333] text-nowrap'>
                      {item.label}
                    </div>
                  </div>
                </Link>
              )
            })}
          </div>
        </CSSTransition>
      </div>
    </Link>
  )
}
/* ------------------------------- NavItem END ------------------------------ */

/* ---------------------------- NavItem 移动端 START --------------------------- */
interface NavItemMobileProps {
  path: string
  children: React.ReactNode
  onClick?: () => void
}

const NavItemMobile: React.FC<NavItemMobileProps> = (props) => {
  const { path, children, onClick } = props
  return (
    <li className='list-none' onClick={onClick}>
      <Link href={path} scroll>
        <div className='flex justify-between items-center py-[1.875rem]'>
          <div className='uppercase'>{children}</div>
          <div className='relative w-[1.375rem] h-[1.375rem]'>
            <Image
              src={arrowRightGreenFill}
              alt='arrow right icon'
              fill
              sizes='66px'
            />
          </div>
        </div>
      </Link>
    </li>
  )
}
/* ----------------------------- NavItem 移动端 END ---------------------------- */

/* ----------------------------- 语言切换器 移动端 START ---------------------------- */
interface LanguageSwitchProps {
  languages: string[]
  current: string
  onSelect: (lang: string) => void
  isFloat: boolean
}

const LanguageSwitch: React.FC<LanguageSwitchProps> = (props) => {
  const { languages, current, onSelect, isFloat } = props

  const displayNames: Record<string, any> = {
    en: 'EN',
    tr: 'Türkçe',
  }

  return (
    <div
      className={`flex items-center rounded-full ${
        isFloat ? 'bg-[#F4F4F4]' : 'bg-white'
      }`}
    >
      {languages.map((lang) => {
        return (
          <div
            key={lang}
            className={`text-[0.875rem] leading-[0.875rem] p-[0.375rem] rounded-full transition-colors duration-200 ease-out ${
              current === lang
                ? 'text-white bg-[#A6C32D]'
                : 'text-[#A6C32D] bg-transparent'
            }`}
            onClick={() => onSelect(lang)}
          >
            {displayNames[lang]}
          </div>
        )
      })}
    </div>
  )
}
/* ----------------------------- 语言切换器 移动端 END ---------------------------- */

/* ---------------------------- 语言切换器 PC 端 START ---------------------------- */
interface LanguageSwitchPCProps {
  languages: string[]
  current: string
  onSelect: (lang: string) => void
  isFloat: boolean
}

const LanguageSwitchPC: React.FC<LanguageSwitchPCProps> = (props) => {
  const { languages, current, onSelect, isFloat } = props

  const displayNames: Record<string, any> = {
    en: 'EN',
    tr: 'Türkçe',
  }

  const dropDownRef = useRef(null)

  return (
    <Dropdown>
      <DropdownTrigger>
        <div className='relative flex items-center cursor-pointer'>
          {/* 地球图标 START */}
          <div
            className={`${
              isFloat ? 'hidden' : ''
            } relative group-hover:hidden w-[0.9375rem] h-[0.9375rem] 2xl:w-[1.4375rem] 2xl:h-[1.4375rem]`}
          >
            <Image
              src={geoWhiteIcon}
              alt='geo icon'
              fill
              sizes='(max-width: 1024px) 0.9375rem, 1.4375rem'
            />
          </div>
          <div
            className={`${
              isFloat ? 'block' : 'hidden'
            } relative group-hover:block w-[0.9375rem] h-[0.9375rem] 2xl:w-[1.4375rem] 2xl:h-[1.4375rem]`}
          >
            <Image
              src={geoBlackIcon}
              alt='geo icon'
              fill
              sizes='(max-width: 1024px) 0.9375rem, 1.4375rem'
            />
          </div>
          {/* 地球图标 END */}
          <div className='w-[0.3125rem] 2xl:w-[0.5rem]' />
          <div className='text-[0.75rem] 2xl:text-[1.125rem]'>
            {displayNames[current]}
          </div>
          <div className='w-[0.3125rem] 2xl:w-[0.5rem]' />
          <div
            className={`${
              isFloat ? 'hidden' : ''
            } relative group-hover:hidden w-[0.6875rem] h-[0.375rem] 2xl:w-[1.0625rem] 2xl:h-[0.5625rem]`}
          >
            <Image
              src={cheveronBottomWhiteIcon}
              alt='cheveron icon'
              fill
              sizes='(max-width: 1024px) 0.6875rem, 1.0625rem'
            />
          </div>
          <div
            className={`${
              isFloat ? 'block' : 'hidden'
            } relative group-hover:block w-[0.6875rem] h-[0.375rem] 2xl:w-[1.0625rem] 2xl:h-[0.5625rem]`}
          >
            <Image
              src={cheveronBottomBlackIcon}
              alt='cheveron icon'
              fill
              sizes='(max-width: 1024px) 0.6875rem, 1.0625rem'
            />
          </div>
        </div>
      </DropdownTrigger>
      <DropdownMenu
        aria-label='Static Actions'
        onAction={(key) => onSelect(key as string)}
      >
        {languages.map((lang) => {
          return (
            <DropdownItem
              key={lang}
              className='text-[0.875rem] 2xl:text-[1rem] px-6 py-2 hover:bg-[#A6C32D] hover:text-white active:bg-[#A6C32D]'
            >
              {displayNames[lang]}
            </DropdownItem>
          )
        })}
      </DropdownMenu>
    </Dropdown>
  )
}
/* ----------------------------- 语言切换器 PC 端 END ----------------------------- */

/* ------------------------------ Header START ------------------------------ */
interface NavigationConfig {
  path: string
  label: string
  anchor?: string
  children?: NavigationConfig[]
}

interface HeaderProps {
  logo: string
  aboutNav: NavigationConfig[]
  newsNav: NavigationConfig[]
  productsNav: NavigationConfig[]
  m: {
    home: string
    about: string
    product: string
    case: string
    news: string
    message: string
    contact: string
    contactCompLabel: string
    contactCompMobile: string
    searchPlaceholder: string
  }
}

const Header: React.FC<HeaderProps> = (props) => {
  const { logo, aboutNav, newsNav, productsNav, m } = props
  const router = useRouter()

  // 当前页面路径名称
  const pathname = usePathname()
  // 将给定的路径与当前路径作匹配
  const matchPathName = useCallback(
    (path: string) => {
      // 当传入路径为首页时作额外判断
      if (path === '/') {
        const count = (pathname.match(/\//g) || []).length
        if (count > 1) {
          return false
        }
        return true
      }

      // 默认情况
      return pathname.includes(path)
    },
    [pathname]
  )

  // 有的页面导航栏前景本身就是黑色的，这个值如果为black，则导航栏永远浮着
  const [initialFrontStyle, setInitialFrontStyle] = useState<'black' | 'white'>(
    'white'
  )

  // 组件加载时判断状态栏初始风格
  useEffect(() => {
    const blackFrontHeaderPages = ['/product-detail/']

    blackFrontHeaderPages.forEach((item) => {
      setInitialFrontStyle(matchPathName(item) ? 'black' : 'white')
    })
  }, [matchPathName])

  // Header 是否“浮”在页面上方，由滚动距离确定
  const { isFloat: baseIsFloat } = useBarFloat()

  // 如果初始前景色风格黑色，则永远浮在上面
  const isFloat = useMemo(() => {
    if (initialFrontStyle === 'black') {
      return true
    } else {
      return baseIsFloat
    }
  }, [baseIsFloat, initialFrontStyle])

  // 移动端下拉菜单是否打开
  const [expanded, setExpanded] = useState(false)
  const dropDownRef = useRef<any>(null)

  // 多语言切换
  const languages = ['en', 'tr']
  const currentLanguage = () => {
    const regExp = /(\w+)/
    const match = regExp.exec(pathname)
    if (match) return match[1]
    return 'en'
  }
  const handleSelectLanguage = (lang: string) => {
    router.replace(`/${lang}`)
    router.refresh()
  }

  // 是否打开搜索
  const [isOpenSearch, setIsOpenSearch] = useState(false)

  const navConfigList: NavigationConfig[] = [
    {
      label: m.home,
      path: '/',
    },
    {
      label: m.about,
      path: '/about',
      anchor: 'anchor',
      children: aboutNav,
    },
    {
      label: m.product,
      path: '/products',
      anchor: 'anchor',
      children: productsNav,
    },
    {
      label: m.case,
      path: '/cases',
      anchor: 'anchor',
    },
    {
      label: m.news,
      path: '/news',
      anchor: 'anchor',
      children: newsNav,
    },
    {
      label: m.message,
      path: '/message',
      anchor: 'anchor',
    },
    {
      label: m.contact,
      path: '/contact',
      anchor: 'anchor',
    },
  ]

  return (
    // 最外层容器，用于添加背景颜色
    <header
      className={`z-50 fixed top-0 left-0 w-screen group hover:text-[#505050] lg:hover:bg-white ${
        isFloat ? 'text-[#505050] bg-white' : 'text-white'
      } transition-colors duration-200 ease-out`}
    >
      {/* 内层容器，用于添加 Border Bottom */}
      <div className='mx-auto max-w-[1680px]'>
        <div className='flex justify-between items-center mx-4 py-3 lg:mx-6 2xl:mx-8 lg:py-0 lg:border-b-white lg:border-b lg:border-opacity-50'>
          {/* Logo 与 PC Nav Bar */}
          <div className='flex items-center'>
            {/* Logo */}
            <Link href='/'>
              <div className='relative flex-shrink-0 w-[2.375rem] h-[1.78125rem] lg:w-[3.1875rem] lg:h-[2.375rem] 2xl:w-[4.75rem] 2xl:h-[3.5625rem]'>
                <Image
                  src={logo}
                  alt='Logo'
                  fill
                  style={{ objectFit: 'cover' }}
                  sizes='(max-width: 1024px) 2.375rem, (max-width: 1536px) 3.1875rem, 4.75rem'
                />
              </div>
            </Link>
            {/* PC Nav Bar */}
            <div className='hidden lg:flex items-center h-full'>
              <div className='w-[1.625rem] 2xl:w-[2.5rem]' />
              <div
                className={`${
                  isFloat ? 'bg-[#404040]' : 'bg-white'
                } w-[1px] h-[1.6875rem] 2xl:h-[2.5rem] group-hover:bg-[#404040] bg-opacity-10 group-hover:bg-opacity-10`}
              ></div>
              <div className='w-[0.875rem] 2xl:w-[1.25rem]' />
              {/* 导航栏 */}
              <nav>
                <ul className='flex items-center'>
                  {navConfigList.map((item) => {
                    return (
                      <NavItem
                        key={item.path}
                        path={item.anchor ? `${item.path}` : item.path}
                        isSelected={matchPathName(item.path)}
                        dropdownItems={item.children || []}
                        isFloat={isFloat}
                      >
                        {item.label}
                      </NavItem>
                    )
                  })}
                </ul>
              </nav>
            </div>
          </div>

          {/* PC端 START */}
          <div className='hidden lg:flex items-center'>
            {/* 联系电话 */}
            <div className='flex items-center'>
              <div className='relative w-4 h-4 2xl:w-[1.5rem] 2xl:h-[1.5rem]'>
                <Image
                  src={phoneIcon}
                  alt='mobile phone'
                  fill
                  sizes='(max-width: 1024px) 1rem, 1.5rem'
                />
              </div>
              <div className='w-[0.6875rem] 2xl:w-4' />
              <div>
                <div className='text-[0.5625rem] leading-[0.8125rem] 2xl:text-[0.875rem] 2xl:leading-[1.25rem]'>
                  {m.contactCompLabel}
                </div>
                <div className='text-[0.75rem] leading-[0.8125rem] 2xl:text-[1.125rem] 2xl:leading-[1.25rem]'>
                  {m.contactCompMobile}
                </div>
              </div>
            </div>
            <div className='w-[1.5625rem] 2xl:w-[2.375rem]' />
            <div
              className={`${
                isFloat ? 'bg-[#404040]' : 'bg-white'
              } w-[1px] h-[1.6875rem] 2xl:h-[2.5rem] group-hover:bg-[#404040] bg-opacity-10 group-hover:bg-opacity-10`}
            />
            <div className='w-[1.5625rem] 2xl:w-[2.375rem]' />
            {/* 搜索图标 START */}
            <div
              className='cursor-pointer'
              onClick={() => setIsOpenSearch(!isOpenSearch)}
            >
              <div
                className={`${
                  isFloat ? 'hidden' : ''
                } relative group-hover:hidden w-[0.9375rem] h-[1.0625rem] 2xl:w-[1.4375rem] 2xl:h-[1.5625rem]`}
              >
                <Image
                  src={searchWhiteIcon}
                  alt='search icon'
                  fill
                  sizes='(max-width: 1024px) 0.9375rem, 1.4375rem'
                />
              </div>
              <div
                className={`${
                  isFloat ? 'block' : 'hidden'
                } relative group-hover:block w-[0.9375rem] h-[1.0625rem] 2xl:w-[1.4375rem] 2xl:h-[1.5625rem]`}
              >
                <Image
                  src={searchBlackIcon}
                  alt='search icon'
                  fill
                  sizes='(max-width: 1024px) 0.9375rem, 1.4375rem'
                />
              </div>
            </div>
            {/* 搜索图标 END */}
            <div className='w-[1.8125rem] 2xl:w-[2.6875rem]' />
            <LanguageSwitchPC
              languages={languages}
              current={currentLanguage()}
              onSelect={handleSelectLanguage}
              isFloat={isFloat}
            />
          </div>
          {/* PC端 END */}

          {/* 移动端 START */}
          <div className='flex items-center lg:hidden'>
            {/* 语言切换器 */}
            <LanguageSwitch
              isFloat={isFloat}
              current={currentLanguage()}
              languages={languages}
              onSelect={handleSelectLanguage}
            />
            <div className='w-[1.46875rem]'></div>
            <div
              className={`${
                isFloat ? 'hidden' : ''
              } relative lg:group-hover:hidden w-[1.09375rem] h-[1.15625rem]`}
              onClick={() => setIsOpenSearch(!isOpenSearch)}
            >
              <Image
                src={searchWhiteIcon}
                alt='search icon'
                fill
                sizes='1.09375rem'
              />
            </div>
            <div
              className={`${
                isFloat ? 'block' : 'hidden'
              } relative lg:group-hover:block w-[1.09375rem] h-[1.15625rem]`}
            >
              <Image
                src={searchBlackIcon}
                alt='search icon'
                fill
                sizes='1.09375rem'
              />
            </div>
            <div className='w-[1.46875rem]'></div>
            <BurgetMenu
              isOpen={expanded}
              isFloat={isFloat}
              onClick={() => setExpanded(!expanded)}
            />
          </div>
          {/* 移动端 END */}
        </div>
        {/* 移动端下拉菜单 */}
        <CSSTransition
          nodeRef={dropDownRef}
          in={expanded}
          timeout={200}
          classNames='nav-item-dropdown'
          unmountOnExit
        >
          <div
            ref={dropDownRef}
            className='absolute top-0 left-0 bg-white w-screen h-screen mt-[3.28125rem] px-4 divide-y'
          >
            {navConfigList.map((item) => {
              return (
                <NavItemMobile
                  key={item.path}
                  path={item.anchor ? `${item.path}` : item.path}
                  onClick={() => setExpanded(false)}
                >
                  {item.label}
                </NavItemMobile>
              )
            })}
          </div>
        </CSSTransition>
      </div>
      <Overlay isOpen={isOpenSearch} setIsOpen={setIsOpenSearch}>
        <Search
          placeholder={m.searchPlaceholder}
          onClose={() => setIsOpenSearch(false)}
        />
      </Overlay>
    </header>
  )
}
/* ------------------------------- Header END ------------------------------- */

export default Header
